﻿using System;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Library
{
    public class Actor : Component, I3DComponent
    {
        public Model model;

        public virtual Vector3 Position { get; set; }
        public Vector3 EulRotation
        {
            get { return MathUtils.MatrixToVector3(Rotation); }
            set { Rotation = MathUtils.Vector3ToMatrix(value); }
        }
        public virtual Matrix Rotation { get; set; }
        public virtual Vector3 Scale { get; set; }
        public virtual BoundingBox BoundingBox
        {
            get
            {
                return new BoundingBox(
                    Position - (Scale / 2),
                    Position + (Scale / 2)
                );
            }
        }

       
        public Actor(Model Model, Vector3 Position)
            : base()
        {
            Setup(Model, Position);
        }

        public Actor(Model Model, Vector3 Position, Screen Parent)
            : base(Parent)
        {
            Setup(Model, Position);
        }

        void Setup(Model Model, Vector3 Position)
        {
            this.model = Model;
            this.Position = Position;
            Scale = Vector3.One;
            EulRotation = Vector3.Zero;
        }

        public override void Draw()
        {

            Camera camera = (Camera)Engine.Services.GetService(typeof(Camera));

            if (camera == null)
            {
                throw new Exception("Camera not found in engine's"
                + "service container, cannot draw");
            }

         
            Matrix world = MathUtils.CreateWorldMatrix(Position, Rotation, Scale);

            Matrix[] transforms = new Matrix[model.Bones.Count];
            model.CopyAbsoluteBoneTransformsTo(transforms);

            Engine.GraphicsDevice.RenderState.AlphaBlendEnable = true;
            Engine.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
            Engine.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
            Engine.GraphicsDevice.RenderState.DepthBufferEnable = true;
 
            foreach (ModelMesh mesh in model.Meshes)
            {
                

                mesh.Draw();
            }
        }
    }
}